package com.kk.score.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kk.score.dao.GradeDao;
import com.kk.score.dao.TaskDao;
import com.kk.score.entity.*;
import com.kk.score.service.ConfigService;
import com.kk.score.service.DepartmentService;
import com.kk.score.service.PushGradeService;
import com.kk.score.service.PushService;
import com.kk.score.utils.PageUtils;
import com.kk.score.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * @author KK
 * @email 409592048@qq.com
 * @date 2022-11-02 12:28:00
 */
@RestController
@RequestMapping("/pushGrade")
public class PushGradeController {
    @Autowired
    private PushGradeService pushGradeService;

    @Autowired
    private GradeDao gradeDao;

    @Autowired
    private ConfigService configService;

    @Autowired
    private DepartmentService departmentService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = pushGradeService.queryPage(params);

        return R.ok().put("data", page);
    }

    /**
     * 保存
     */
    @RequestMapping("/context")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R context(@RequestBody Map<String, Object> params) {
        return R.ok().put("data", configService.update(new ConfigEntity((String) params.get("context")), new LambdaQueryWrapper<ConfigEntity>().eq(ConfigEntity::getStatus, 1)));
    }

    /**
     * 保存
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/save")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R save(@RequestBody PushGradeEntity push) {
        String departmentUid = push.getDepartmentUid();
        String year = push.getYear();
        PushGradeEntity one = pushGradeService.getOne(new LambdaQueryWrapper<PushGradeEntity>().eq(PushGradeEntity::getYear, year).eq(PushGradeEntity::getDepartmentUid, departmentUid));
        if (!Objects.isNull(one)) {
            return R.error("该单位今年满意度调查任务已生成");
        }
        pushGradeService.save(push);
        //给所有可用的部门下的用户创建任务
        int count = gradeDao.insertAll(push);
        return R.ok().put("data", count);
    }

    /**
     * 批量开启任务
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/saveAll")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R saveAll(@RequestBody PushGradeEntity push) {
        String year = push.getYear();
        //获取所有可用的单位
        List<DepartmentEntity> list = departmentService.list(new LambdaQueryWrapper<DepartmentEntity>().eq(DepartmentEntity::getIs_unit, 1).eq(DepartmentEntity::getStatus, 1));
        //排除今年已经生成任务的单位
        List<String> uids = new ArrayList<>();
        List<PushGradeEntity> pushList = pushGradeService.list(new LambdaQueryWrapper<PushGradeEntity>().eq(PushGradeEntity::getYear, year));
        for (PushGradeEntity gradeEntity : pushList) {
            uids.add(gradeEntity.getDepartmentUid());
        }
        List<PushGradeEntity> insertPushs = new ArrayList<>();
        //创建所有未开启任务的单位
        for (DepartmentEntity entity : list) {
            String uid = entity.getUid();
            if (!uids.contains(uid)){
                insertPushs.add(new PushGradeEntity(uid,year,push.getStartTime(),push.getEndTime()));
            }
        }
        pushGradeService.saveOrUpdateBatch(insertPushs);
        //给所有可用的部门下的用户创建任务
        for (PushGradeEntity insertPush : insertPushs) {
            gradeDao.insertAll(insertPush);
        }
        return R.ok().put("data", insertPushs.size());
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/update")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R update(@RequestBody PushGradeEntity push) {
        pushGradeService.update(push, new LambdaQueryWrapper<PushGradeEntity>().eq(PushGradeEntity::getDepartmentUid, push.getDepartmentUid()).eq(PushGradeEntity::getYear, push.getYear()));
        //修改grade任务中的时间
        gradeDao.updateTask(new GradeEntity(push.getStartTime(), push.getEndTime(), push.getUid()));
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R delete(@RequestBody String[] uids) {
        pushGradeService.removeByIds(Arrays.asList(uids));

        return R.ok();
    }

    /**
     * 编辑次数
     */
    @PostMapping("/count")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R count(@RequestBody Map<String,String> params) {
        configService.update(new ConfigEntity(params.get("s")),new LambdaQueryWrapper<ConfigEntity>().eq(ConfigEntity::getStatus,2));
        configService.update(new ConfigEntity(params.get("bad")),new LambdaQueryWrapper<ConfigEntity>().eq(ConfigEntity::getStatus,3));
        return R.ok();
    }

}
